package com.demo.common.redis.config;

import com.demo.common.redis.component.RedisKeys;
import com.demo.common.redis.component.RedisUtil;
import com.demo.common.redis.component.StringRedisUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * @author 001
 */
public class RedisConfigAutoConfiguration {

    @Resource
    private Environment environment;

    @Bean("redisTemplate")
    @SuppressWarnings(value = {"unchecked","rawtypes"})
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisKeys redisKeys() {
        return new RedisKeys(environment);
    }

    @Bean
    @ConditionalOnBean(RedisTemplate.class)
    public RedisUtil redisUtil(RedisTemplate<String,Object> redisTemplate) {
        return new RedisUtil(redisTemplate);
    }

    @Bean
    @ConditionalOnBean(RedisTemplate.class)
    public StringRedisUtil stringRedisUtil(StringRedisTemplate stringRedisTemplate) {
        return new StringRedisUtil(stringRedisTemplate);
    }
}
